package com.k2data.k2app.service.v2;

import com.k2data.k2app.domain.po.v1.RFile;
import com.k2data.k2app.domain.po.v2.FeedbackAnswerPO;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.RFileMapper;
import com.k2data.k2app.mapper.v2.FeedbackAnswerMapper;
import com.k2data.k2app.rest.InstanceClient;
import com.k2data.k2app.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author cuilibo@k2data.com.cn
 * @date 2018年05月22日10:45:05
 */
@Service
public class FeedbackAnswerService {


    @Autowired
    private FeedbackAnswerMapper feedbackAnswerMapper;
    @Autowired
    private RFileMapper rFileMapper;

    @Autowired
    private InstanceClient instanceClient;


    @Autowired
    public FeedbackAnswerService () {

    }

    /**
     * 插入客户事件
     *
     * @param po 实体
     * @return 插入 id
     * @throws K2ResponseException 客户 id 没找到, eventType 没找到
     */
    @Transactional
    public Long insert(FeedbackAnswerPO po) throws K2ResponseException {
        po.setAnswerTime(LocalDateTime.now());
        feedbackAnswerMapper.insertSelective(po);

        List<RFile> rFiles = RFile.updateFiles(po.getId(),po.getFileList(),"feedbackAnswer");
        if(rFiles!=null && rFiles.size()>0){
            rFileMapper.insertBatch(rFiles);
        }
        return po.getId();
    }

    @Transactional
    public int update(FeedbackAnswerPO po) throws K2ResponseException {
        return feedbackAnswerMapper.updateByPrimaryKey(po);
    }


    public List<FeedbackAnswerPO> list(FeedbackAnswerPO cond) {
        List<FeedbackAnswerPO> eventList = feedbackAnswerMapper.selectAnswers(cond);
        eventList.forEach(item -> {
            if (!StringUtils.isBlank(item.getUserPhoto())) {
                item.setUserPhoto(instanceClient.getGatewayUrl() + Paths.get("/static/", item.getUserPhoto()).toString());
            } else {
                item.setUserPhoto("");
            }
            //为所有文件设置文件路径
            if(item.getFileList() != null && item.getFileList().size()>0){
                List<RFile> byCustomerId = item.getFileList();
                for(RFile rFile:byCustomerId){
                    //设置文件路径
                    rFile.setFileUrl(instanceClient.getGatewayUrl() + Paths.get("/static/", rFile.getFileUrl()).toString());
                }
                item.setFileList(byCustomerId);
            }
        });
        return eventList;
    }
}
